"use client";
import React, { useEffect, useState } from "react";
import { Card, Avatar, Skeleton, Tooltip, Image } from "antd";
import Link from "next/link";
import { showMoodPost, getPostCommentNum } from "@/api/moodPostController";
import { CommentOutlined, LikeOutlined, FireOutlined } from "@ant-design/icons";

interface HotTopic {
  id: number;
  content: string;
  userName: string;
  thumbNum: number;
  commentNum: number;
  userAvatar?: string;
  photoName?: string; // 图片地址，可能是逗号分隔的多个地址
}

const HotTopicsCard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [hotTopics, setHotTopics] = useState<HotTopic[]>([]);

  useEffect(() => {
    const fetchHotTopics = async () => {
      try {
        setLoading(true);
        const res = await showMoodPost({});
        // @ts-ignore - API 返回类型处理
        if (res.code === 0 && Array.isArray(res.data)) {
          // 获取所有帖子
          let posts = [...res.data];
          
          // 获取每个帖子的评论数
          const postsWithCommentNum = await Promise.all(
            posts.map(async (post) => {
              try {
                const commentNumRes = await getPostCommentNum(post.id);
                return {
                  ...post,
                  commentNum: commentNumRes.data || 0
                };
              } catch (error) {
                return {
                  ...post,
                  commentNum: 0
                };
              }
            })
          );
          
          // 按点赞数排序，取前3条
          const sortedPosts = postsWithCommentNum
            .sort((a, b) => (b.thumbNum || 0) - (a.thumbNum || 0))
            .slice(0, 3);
            
          setHotTopics(sortedPosts);
        }
      } catch (error) {
        console.error("Failed to fetch hot topics:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchHotTopics();
  }, []);

  // 从逗号分隔的图片地址中获取第一张图片
  const getFirstImage = (photoName?: string): string | undefined => {
    if (!photoName) return undefined;
    const images = photoName.split(',');
    return images.length > 0 ? images[0] : undefined;
  };

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <FireOutlined style={{ color: '#ff4d4f', marginRight: 8 }} />
          <span>精选饭点</span>
        </div>
      }
      headStyle={{
        fontSize: 16,
        fontWeight: 600,
        borderBottom: "1px solid #f0f0f0",
        paddingLeft: 16,
      }}
      bodyStyle={{ padding: "12px 16px" }}
      style={{ marginBottom: 16, marginTop: 16 }}
    >
      {loading ? (
        <div style={{ padding: "8px 0" }}>
          <Skeleton active paragraph={{ rows: 1 }} />
          <Skeleton active paragraph={{ rows: 1 }} />
          <Skeleton active paragraph={{ rows: 1 }} />
        </div>
      ) : (
        <div>
          {hotTopics.map((topic, index) => (
            <Link href={`/mood/${topic.id}`} key={topic.id}>
              <div
                style={{
                  display: "flex",
                  padding: "12px 0",
                  borderBottom: index < hotTopics.length - 1 ? "1px solid #f0f0f0" : "none",
                  cursor: "pointer",
                  transition: "background-color 0.3s",
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.02)";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = "transparent";
                }}
              >
                <div
                  style={{
                    minWidth: 24,
                    textAlign: "center",
                    fontWeight: 600,
                    fontSize: 15,
                    color: index < 3 ? "#ff4d4f" : "#888",
                    marginRight: 12,
                  }}
                >
                  {index + 1}
                </div>
                <div style={{ flex: 1, overflow: "hidden" }}>
                  <div style={{ display: "flex", gap: 12 }}>
                    <div
                      style={{
                        flex: 1,
                        fontSize: 14,
                        fontWeight: 500,
                        color: "#333",
                        marginBottom: 6,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        display: "-webkit-box",
                        WebkitLineClamp: 2,
                        WebkitBoxOrient: "vertical",
                        lineHeight: "1.5",
                        maxHeight: "3em", // 确保最多显示两行
                        wordBreak: "break-word"
                      }}
                    >
                      {topic.content}
                    </div>
                    {getFirstImage(topic.photoName) && (
                      <div style={{ flexShrink: 0, width: 60, height: 60 }}>
                        <img
                          src={getFirstImage(topic.photoName)}
                          alt="帖子图片"
                          style={{ 
                            width: '100%', 
                            height: '100%', 
                            objectFit: 'cover', 
                            borderRadius: 4 
                          }}
                        />
                      </div>
                    )}
                  </div>
                  <div
                    style={{
                      fontSize: 12,
                      color: "#999",
                      display: "flex",
                      alignItems: "center",
                    }}
                  >
                    <Tooltip title="评论数">
                      <span style={{ display: 'flex', alignItems: 'center' }}>
                        <CommentOutlined style={{ fontSize: 12, marginRight: 4 }} />
                        {topic.commentNum || 0}
                      </span>
                    </Tooltip>
                    <span style={{ margin: "0 8px" }}>•</span>
                    <Tooltip title="点赞数">
                      <span style={{ display: 'flex', alignItems: 'center' }}>
                        <LikeOutlined style={{ fontSize: 12, marginRight: 4 }} />
                        {topic.thumbNum || 0}
                      </span>
                    </Tooltip>
                  </div>
                </div>
              </div>
            </Link>
          ))}
          
          {hotTopics.length === 0 && (
            <div style={{ textAlign: "center", color: "#999", padding: "20px 0" }}>
              暂无热门话题
            </div>
          )}
        </div>
      )}
    </Card>
  );
};

export default HotTopicsCard; 